// 扩展颜色类型定义
type RGB = `rgb(${number}, ${number}, ${number})`;
type RGBA = `rgba(${number}, ${number}, ${number}, ${number})`;
type HEX = `#${string}`;
type HSL = `hsl(${number}, ${number}%, ${number}%)`;
type HSLA = `hsla(${number}, ${number}%, ${number}%, ${number})`;
type ColorName = 'red' | 'blue' | 'green' | 'black' | 'white' | 'transparent' | 'currentColor';

// 完整的颜色类型
type CSSColor = RGB | RGBA | HEX | HSL | HSLA | ColorName;

interface WaterMarkConfig {
  fontSize: number;
  text: string;
  rotate: number;
  zIndex: number;
  color: CSSColor;
  [key: string]: any;
}

const WaterMark = {
  mounted(el: any, binding: any) {
    const createWatermarkElement = (config: WaterMarkConfig) => {
      const canvas = document.createElement('canvas');
      canvas.width = 250;
      canvas.height = 150;

      const ctx = canvas.getContext('2d');
      if (!ctx) return;
      ctx.font = `${config.fontSize}px Arial`;
      ctx.fillStyle = config.color;
      ctx.textAlign = 'center';
      ctx.textBaseline = 'middle';
      ctx.translate(canvas.width / 2, canvas.height / 2);
      ctx.rotate((Math.PI / 180) * config.rotate);
      ctx.fillText(config.text, 0, 0);
      ctx.scale(0.1, 0.1);

      const watermarkUrl = canvas.toDataURL('image/png');

      const div = document.createElement('div');
      div.style.cssText = `
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        pointer-events: none;
        background-image: url(${watermarkUrl});
        background-repeat: repeat;
        z-index: ${config.zIndex};
      `;
      return div;
    };
    const config: WaterMarkConfig = {
      text: '德悟庵机密文件',
      fontSize: 20,
      color: 'rgba(0, 0, 0, 0.1)',
      rotate: -20,
      zIndex: 9999,
      ...binding.value,
    };
    // 创建水印元素
    const watermarkDiv = createWatermarkElement(config);
    el.style.position = 'relative';
    el.appendChild(watermarkDiv);
    el._watermarkDiv = watermarkDiv;

    // 防止水印被删除
    const observer = new MutationObserver((mutations: any) => {
      mutations.forEach(() => {
        if (!el.contains(watermarkDiv)) {
          el.appendChild(watermarkDiv);
        }
      });
    });

    observer.observe(el, {
      childList: true,
      subtree: true,
      attributes: true,
    });

    el._watermarkObserver = observer;
  },

  updated(el: any, binding: any) {
    if (JSON.stringify(binding.value) !== JSON.stringify(binding.oldValue)) {
      this.unmounted(el);
      this.mounted(el, binding);
    }
  },

  unmounted(el: any) {
    if (el._watermarkDiv) {
      el.removeChild(el._watermarkDiv);
      delete el._watermarkDiv;
    }
    if (el._watermarkObserver) {
      el._watermarkObserver.disconnect();
      delete el._watermarkObserver;
    }
  },
};

export default WaterMark;
